package com.douqu.game.auth.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.bean.core.pay.alipay.AlipayConfig;
import com.bean.core.pay.tenpay.bean.TenpayTradeNotifyInfo;
import com.bean.core.pay.tenpay.bean.TenpayTradeReceiptInfo;
import com.bean.core.pay.tenpay.util.XMLUtil;
import com.bean.core.util.HttpJsonUtils;
import com.bean.core.util.MD5Utils;
import com.bean.core.util.TimeUtils;
import com.bean.core.util.Utils;
import com.douqu.game.auth.database.mapper.ServerMapper;
import com.douqu.game.auth.database.model.ServerModel;
import com.douqu.game.auth.server.WorldManager;
import com.douqu.game.auth.service.OrderRecordService;
import com.douqu.game.auth.service.PlayerService;
import com.douqu.game.auth.web.request.AliCheckOrderReqParam;
import com.douqu.game.auth.web.request.PPCheckOrderReqParam;
import com.douqu.game.auth.web.request.YjCheckOrderReqParam;
import com.douqu.game.core.database.model.OrderRecordModel;
import com.douqu.game.core.e.E_RechargeStatus;
import com.douqu.game.core.e.ReturnMessage;
import com.douqu.game.core.factory.ConstantFactory;
import com.douqu.game.core.factory.HttpFactory;
import com.douqu.game.core.factory.PlatformFactory;
import com.douqu.game.core.protobuf.SGCommonProto;
import com.douqu.game.core.util.ApplePayUtils;
import com.douqu.game.core.util.LogUtils;
import com.douqu.game.core.util.PayUtils;
import com.douqu.game.core.web.AppStoreNotifyParam;
import com.douqu.game.core.web.RechargeCallBackParam;
import com.douqu.game.core.web.request.RechargeParam;
import com.douqu.game.core.web.response.BaseResponseDto;
import com.douqu.game.core.web.response.ErrorResponseDto;
import org.jdom2.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
* @author wangzhenfei
*         2018-01-17 15:42
*         易接消费回调
*/
@RestController
public class PayController {

    public final static String PARAM_ERROR = "PARAM_ERROR";
    public final static String SUCCESS_UPPER = "SUCCESS";
    public final static String FAIL_UPPER = "FAIL";
    public final static String ERROR_UPPER = "ERROR";

    public final static String SUCCESS_LOWER = "success";
    public final static String FAIL_LOWER = "fail";

    public final static String SUCCESS_1 = "1";
    public final static String FAIL_0 = "0";

    @Autowired
    PlayerService playerService;

    @Autowired
    ServerMapper serverMapper;

    @Autowired
    OrderRecordService orderRecordService;

    @RequestMapping(value = "/pay/test")
    public BaseResponseDto test(String password) throws IOException
    {
        LogUtils.error("收到测试数据 -> " + password);
        LogUtils.info("request -> " + password);
        return new BaseResponseDto(ReturnMessage.SUCCESS);
    }

    @ResponseBody
    @RequestMapping(value = HttpFactory.PAY_INIT, method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public BaseResponseDto initRecharge(@RequestBody OrderRecordModel orderRecordModel)
    {
        orderRecordModel.setStatus(E_RechargeStatus.NO_PAY.getCode());
        int count = orderRecordService.createOrder(orderRecordModel);

        return count == 1 ? new BaseResponseDto(ReturnMessage.SUCCESS) : new ErrorResponseDto(ReturnMessage.FAILURE);
    }

    /**
     * 易接的回调
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = HttpFactory.PAY_YJ_CHECK)
    public void checkOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter w = response.getWriter();
        YjCheckOrderReqParam orderReqDto = new YjCheckOrderReqParam();
        orderReqDto.init(request);
        LogUtils.info("回调参数：" + orderReqDto.toString());
        if (orderReqDto.isResultOk()) {
            // 此处CP可以持久化消费记录
            //st==1是支付成功，才能给用户发道具
            if (orderReqDto.isSuccess()) {
                Integer count = orderRecordService.findCount(orderReqDto.getInnerParam().getObjectIndex(), orderReqDto.getTcd());
                if (count == null || count == 0) { //没有成功的记录，发送奖励
                    //TODO 发送奖励
                    //获取服务器id
                    Integer serverId = orderReqDto.getInnerParam().getServerId();
                    ServerModel serverModel = serverMapper.selectByPrimaryKey(serverId);
                    if (serverModel == null) {
                        LogUtils.error("服务器找不到 id为:" + serverId);
                        w.write("ERROR");
                    } else {
                        RechargeParam rechargeParam = orderReqDto.getInnerParam();
                        String payType = PayUtils.getEnumType(SGCommonProto.E_RECHARGE_TYPE.RECHARGE_TYPE_YJ.name());
                        boolean result = PayUtils.checkOrderFromMainServer(serverModel.getMainServerRequestUrl(), serverId, rechargeParam.getObjectIndex(), orderReqDto.getCbi(),
                                                                            rechargeParam.getOutTradeNo(), orderReqDto.getTcd(), orderReqDto.getFee(), payType, orderReqDto.getSdk(), false);
                        if(result)
                        {
                            orderRecordService.updateOrder(orderReqDto.getOrderRecordModel(payType), true);
                            LogUtils.warn("易接冲值成功 -> " + rechargeParam.getOutTradeNo());
                            w.write(SUCCESS_UPPER);
                        }
                        else
                        {
                            LogUtils.debug("主服务器冲值回调返回错误!");
                            w.write(ERROR_UPPER);
                        }
                    }

                } else {
                    LogUtils.warn("该订单重复验证 -> outTradeNo:" + orderReqDto.getInnerParam().getOutTradeNo());
                    w.write(SUCCESS_UPPER);
                }
            }
            // 操作成功后需要返回SUCCESS告诉易接服务器已经接收成功

        } else {
            // 返回ERROR易接服务器会根据一定的策略重新同步消费记录给CP
            LogUtils.error(ERROR_UPPER);
            w.write(ERROR_UPPER);
        }
        w.flush();
        w.close();
    }

    /**
     * 支付宝的回调
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = HttpFactory.PAY_NOTIFY_ALIPAY)
    public String alipayNotify(HttpServletRequest request, HttpServletResponse response) {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        LogUtils.warn("支付宝回调 -> " + params.toString());
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean flag = false;
        try {
            flag = AlipaySignature.rsaCheckV1(params, AlipayConfig.ali_public_key, AlipayConfig.charset, AlipayConfig.SIGN_RSA2);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (!flag) {
            LogUtils.error("回调结果：fail");
            return FAIL_LOWER;
        }
        LogUtils.debug("回调结果：" + (flag ? "success" : "fail"));
        AliCheckOrderReqParam orderReqDto = new AliCheckOrderReqParam(params);
        if (orderReqDto.isSuccess()) {
            Integer count = orderRecordService.findCount(orderReqDto.getInnerParam().getObjectIndex(), orderReqDto.getTrade_no());
            if (count == null || count == 0) { //没有成功的记录，发送奖励
                //TODO 发送奖励
                //获取服务器id
                Integer serverId = orderReqDto.getInnerParam().getServerId();
                ServerModel serverModel = serverMapper.selectByPrimaryKey(serverId);
                if (serverModel == null) {
                    LogUtils.error("服务器找不到 id为:" + serverId);
                    return FAIL_LOWER;
                } else {
                    RechargeParam rechargeParam = orderReqDto.getInnerParam();
                    String payType = PayUtils.getEnumType(SGCommonProto.E_RECHARGE_TYPE.RECHARGE_TYPE_ALI.name());
                    boolean result = PayUtils.checkOrderFromMainServer(serverModel.getMainServerRequestUrl(), rechargeParam.getServerId(), rechargeParam.getObjectIndex(), orderReqDto.getPassback_params(),
                                                                        rechargeParam.getOutTradeNo(), orderReqDto.getTrade_no(), orderReqDto.getFee(), payType, payType, false);
                    if(result)
                    {
                        orderRecordService.updateOrder(orderReqDto.getOrderRecordModel(payType), true);
                        LogUtils.warn("支付宝冲值成功 -> " + rechargeParam.getOutTradeNo());
                        return SUCCESS_LOWER;
                    }
                    else
                    {
                        LogUtils.debug("主服务器冲值回调返回错误!");
                        return FAIL_LOWER;
                    }
                }

            } else {
                LogUtils.warn("该订单重复验证 -> outTradeNo:" + orderReqDto.getInnerParam().getOutTradeNo());
                return SUCCESS_LOWER;
            }
        } else {
            LogUtils.error("支付状态判断：fail");
            return FAIL_LOWER;
        }
    }

    @ResponseBody
    @RequestMapping(value = HttpFactory.PAY_NOTIFY_TENPAY)
    public void tenpayNotify(HttpServletRequest request, HttpServletResponse response)
    {
        try {
            ServletInputStream inputStream = request.getInputStream();
            int BUFFER_SIZE = 4096;
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] data = new byte[BUFFER_SIZE];
            int count = -1;
            while ((count = inputStream.read(data, 0, BUFFER_SIZE)) != -1) {
                outStream.write(data, 0, count);
            }
            byte[] outByte = outStream.toByteArray();
            outStream.close();
            String requestXmlContent = new String(outByte, "utf-8");

            LogUtils.info("Tenpay notify request : " + requestXmlContent);

            TenpayTradeNotifyInfo tradeNotifyInfo = TenpayTradeNotifyInfo.parseFromXML(requestXmlContent);

            TenpayTradeReceiptInfo tradeReceiptInfo = TenpayTradeReceiptInfo.initFailInfo();
            if(tradeNotifyInfo != null){
                OrderRecordModel orderRecordModel = orderRecordService.findByOutTradeNo(tradeNotifyInfo.getOut_trade_no());
                if(orderRecordModel != null)
                {
                    if (tradeNotifyInfo.verifySign()) {
                        if(orderRecordModel.getStatus() == E_RechargeStatus.PAY_SUCCESS.getCode())
                        {
                            LogUtils.warn("该订单重复验证 -> outTradeNo:" + tradeNotifyInfo.getOut_trade_no());
                            tradeReceiptInfo = TenpayTradeReceiptInfo.initSuccessInfo();
                        }
                        else
                        {
                            if(tradeNotifyInfo.getResult_code().equals(SUCCESS_UPPER))
                            {
                                if(tradeNotifyInfo.getResult_code().equals(SUCCESS_UPPER))
                                {
                                    //自定义参数
                                    RechargeParam rechargeParam = new RechargeParam(tradeNotifyInfo.getAttach());
                                    ServerModel serverModel = serverMapper.selectByPrimaryKey(rechargeParam.getServerId());
                                    if (serverModel == null)
                                    {
                                        LogUtils.error("服务器找不到 id为:" + rechargeParam.getServerId());
                                    }
                                    else
                                    {
                                        String payType = PayUtils.getEnumType(SGCommonProto.E_RECHARGE_TYPE.RECHARGE_TYPE_WECHAT.name());
                                        boolean result = PayUtils.checkOrderFromMainServer(serverModel.getMainServerRequestUrl(), rechargeParam.getServerId(), rechargeParam.getObjectIndex(), tradeNotifyInfo.getAttach(),
                                                                                            tradeNotifyInfo.getOut_trade_no(), tradeNotifyInfo.getOut_trade_no(), tradeNotifyInfo.getTotal_fee(), payType, payType, false);
                                        if(result)
                                        {
                                            orderRecordModel.paySuccess(rechargeParam.getClientParam(), rechargeParam.getDiamonds(), rechargeParam.getLv(), payType, payType, rechargeParam.getRuleId(), tradeNotifyInfo.getOut_trade_no());
                                            orderRecordService.updateOrder(orderRecordModel, false);
                                            LogUtils.warn("微信冲值成功 -> " + tradeNotifyInfo.getOut_trade_no());
                                            tradeReceiptInfo = TenpayTradeReceiptInfo.initSuccessInfo();
                                        }
                                        else
                                        {
                                            LogUtils.debug("主服务器冲值回调返回错误!");
                                        }
                                    }
                                }
                                else
                                {
                                    LogUtils.error("支付失败 -> " + tradeNotifyInfo.getResult_code());
                                    tradeReceiptInfo = TenpayTradeReceiptInfo.initSuccessInfo();
                                }
                            }
                            else
                            {
                                LogUtils.error("Tenpay notify Error -> " + tradeNotifyInfo.getReturn_code());
                            }
                        }
                    } else {
                        LogUtils.error("Tenpay notify invalid signature, tenpay signature verification failed -> request : " + requestXmlContent);
                    }

                    String responseXml = tradeReceiptInfo.createRequestXML();
                    LogUtils.info("tenpay notify " + tradeNotifyInfo.getOut_trade_no() + " -> response :" + responseXml);
                    PrintWriter out = response.getWriter();
                    out.write(responseXml);
                    out.flush();
                    out.close();
                }
                else
                {
                    LogUtils.error("OrderRecordModel is null -> outTradeNo:" + tradeNotifyInfo.getOut_trade_no());
                }
            }
        } catch (Exception e) {
            LogUtils.errorException(e);
        }
    }


    /**
     * 苹果支付的回调
     *
     * @throws Exception 苹果内购支付
     * @throws
     * @Title: doIosRequest
     * @Description:Ios客户端内购支付
     */
    @RequestMapping(value = HttpFactory.PAY_NOTIFY_APPLEPAY, method = RequestMethod.POST)
    public BaseResponseDto appstoreNotify(@RequestBody AppStoreNotifyParam reqDto)
    {
        LogUtils.info("收到苹果冲值验证----------->" + JSONObject.toJSONString(reqDto));
        ReturnMessage errorInfo = reqDto.check();
        if(errorInfo != null)
            return new ErrorResponseDto(errorInfo);

        ServerModel serverModel = null;
        try{
            serverModel = serverMapper.selectByPrimaryKey(reqDto.getServerId());
            if (serverModel == null) {
                LogUtils.error("服务器找不到 id为:" + reqDto.getServerId());
                return new ErrorResponseDto(ReturnMessage.PARAM_ERROR);
            }
        }catch (Exception e){
            LogUtils.error("参数错误 -> serverId:" + reqDto);
            return new ErrorResponseDto(ReturnMessage.PARAM_ERROR);
        }

        LogUtils.info("notify/appstore outTradeNo：" + reqDto.getOutTradeNo());
        //因为查询苹果比较慢，所以单独开启线程处理
        final ServerModel finalServerModel = serverModel;
        WorldManager.getInstance().startThread(() ->{

            LogUtils.info("开始验证苹果冲值订单 -> " + reqDto.getOutTradeNo());
            String errorNotifyUrl = finalServerModel.getMainServerRequestUrl() + HttpFactory.ORDER_ERROR_NOTIFY;
            RechargeCallBackParam resParam = new RechargeCallBackParam();
            resParam.setObjectIndex(reqDto.getPlayerIndex());
            String payType = PayUtils.getEnumType(SGCommonProto.E_RECHARGE_TYPE.RECHARGE_TYPE_APPSTORE.name());
            resParam.setChannel(payType);
            resParam.setPayType(payType);
            String checkString = finalServerModel.getId() + ConstantFactory.RECHARGE_KEY + TimeUtils.getCurrentTime(TimeUtils.YYYYMMDD);
            resParam.setPassword(MD5Utils.encodeUppercase(checkString));
            resParam.setOutTradeNo(reqDto.getOutTradeNo());
            try{
                String outTradeNo = reqDto.getOutTradeNo();
                OrderRecordModel tradeNoOrder = orderRecordService.findByOutTradeNo(outTradeNo);
                OrderRecordModel transactionOrder = null;
                if (tradeNoOrder != null && !Utils.isNullOrEmpty(tradeNoOrder.getTcd()) && tradeNoOrder.getTcd().equals(reqDto.getTransactionId()))
                {
                    LogUtils.error("数据库已经存了苹果订单号，但跟验证的参数不一样 -> 数据库的:" + tradeNoOrder.getTcd() + "  验证的:" + reqDto.getTransactionId());
                    resParam.setErrorMsg(ReturnMessage.PARAM_ERROR.getMsg());
                    HttpJsonUtils.httpPost(errorNotifyUrl, resParam.toJSONObject());
                }
                else if(tradeNoOrder != null && tradeNoOrder.getStatus() == E_RechargeStatus.PAY_SUCCESS.getCode())
                {
                    LogUtils.warn("该订单重复验证 -> outTradeNo:" + tradeNoOrder.getOutTradeNo());
                    resParam.setErrorMsg(ReturnMessage.REPEAT_REQUEST.getMsg());
                    HttpJsonUtils.httpPost(errorNotifyUrl, resParam.toJSONObject());
                }
                else
                {
                    boolean canVerify = false;
                    if(tradeNoOrder == null)
                    {
                        transactionOrder = orderRecordService.findByTcd(reqDto.getTransactionId());
                        if(transactionOrder != null && transactionOrder.getStatus() == E_RechargeStatus.PAY_SUCCESS.getCode())
                        {
                            LogUtils.warn("该订单重复验证 -> outTradeNo:" + transactionOrder.getOutTradeNo());
                            resParam.setErrorMsg(ReturnMessage.REPEAT_REQUEST.getMsg());
                            HttpJsonUtils.httpPost(errorNotifyUrl, resParam.toJSONObject());
                        }
                        else
                        {
                            //继续验证
                            canVerify = true;
                        }
                    }
                    else
                    {
                        //继续验证
                        canVerify = true;
                    }

                    if(canVerify)
                    {
                        String verifyResult = ApplePayUtils.buyAppVerify(reqDto.getPayload(), false);            //1.先线上测试    发送平台验证
                        if (verifyResult == null) {                                            // 苹果服务器没有返回验证结果
                            LogUtils.error("正式环境无此订单信息!");
                        } else {                                                                // 苹果验证有返回结果
                            LogUtils.info("线上 -> " + reqDto.getOutTradeNo());
                            JSONObject job = JSONObject.parseObject(verifyResult);
                            String states = job.getString("status");

                            if ("21007".equals(states)) {                                            //是沙盒环境，应沙盒测试，否则执行下面
                                verifyResult = ApplePayUtils.buyAppVerify(reqDto.getPayload(), true);            //2.再沙盒测试  发送平台验证
                                LogUtils.info("沙盒环境");
                                job = JSONObject.parseObject(verifyResult);
                                states = job.getString("status");
                            }

                            LogUtils.info("苹果平台返回值：job" + job);
                            if (states.equals("0"))
                            { // 前端所提供的收据是有效的    验证成功
                                String r_receipt = job.getString("receipt");
                                JSONObject returnJson = JSONObject.parseObject(r_receipt);
                                JSONArray jsonArray = returnJson.getJSONArray("in_app");
                                boolean isIn = false;
                                String transactionId = reqDto.getTransactionId();
                                String productId = "";//根据这个productId去确定真实金额
                                for (int i = 0; i < jsonArray.size(); i++) {
                                    if (reqDto.getTransactionId().equals(jsonArray.getJSONObject(i).getString("transaction_id"))) {
                                        isIn = true;
                                        productId = jsonArray.getJSONObject(i).getString("product_id");
                                        break;
                                    }
                                }

                                //如果单号一致  则保存到数据库
                                if (isIn)
                                {
                                    LogUtils.info("苹果验证成功,现在开始本地验证是否这个订单已经处理过");
                                    OrderRecordModel orderRecordModel = null;
                                    if(tradeNoOrder != null)
                                    {
                                        orderRecordModel = tradeNoOrder;
                                    }
                                    else if(transactionOrder != null)
                                    {
                                        orderRecordModel = transactionOrder;
                                    }

                                    if (orderRecordModel != null && orderRecordModel.getStatus() == E_RechargeStatus.PAY_SUCCESS.getCode())
                                    {
                                        LogUtils.info("订单 -> tcd:" + transactionId + " 已经验证过");
                                        resParam.setErrorMsg(ReturnMessage.REPEAT_REQUEST.getMsg());
                                        HttpJsonUtils.httpPost(errorNotifyUrl, resParam.toJSONObject());
                                    }
                                    else
                                    {
                                        int rechargeId = 0;
                                        if(orderRecordModel == null)
                                        {
                                            //根据玩家流水号和服务器去查找
                                            orderRecordModel = orderRecordService.findNoPayOrder(reqDto.getPlayerIndex(), finalServerModel.getId());
                                        }

                                        rechargeId = orderRecordModel == null ? 0 : orderRecordModel.getRechargeId();

                                        if(rechargeId == 0)
                                        {
                                            LogUtils.error("获取rechargeId错误 -> playerIndex:" + reqDto.getPlayerIndex() + ", serverId:" + finalServerModel.getId());
                                            resParam.setErrorMsg(ReturnMessage.PARAM_ERROR.getMsg());
                                            HttpJsonUtils.httpPost(errorNotifyUrl, resParam.toJSONObject());
                                        }
                                        else
                                        {
                                            JSONObject diamondResult = HttpJsonUtils.httpPost(finalServerModel.getMainServerRequestUrl() + HttpFactory.MANAGER_GET_RECHARGE_MONEY + "?rechargeId=" + rechargeId);
                                            if(diamondResult == null)
                                            {
                                                LogUtils.error("从主服获取钻石数量错误 -> rechargeId:" + rechargeId);
                                                resParam.setErrorMsg(ReturnMessage.PARAM_ERROR.getMsg());
                                                HttpJsonUtils.httpPost(errorNotifyUrl, resParam.toJSONObject());
                                            }
                                            else
                                            {
                                                int diamond = diamondResult.getJSONObject("data").getInteger("diamond");
                                                int rmb = diamondResult.getJSONObject("data").getInteger("rmb") * 100;//转为分

                                                String rechargeParam = PayUtils.createRechargeParam(reqDto.getPlayerIndex(), rechargeId, reqDto.getServerId(), reqDto.getPlayerLv(), diamond, reqDto.getServerRuleId(), null, null, outTradeNo);
                                                resParam.setRechargeParam(rechargeParam);
                                                resParam.setTcd(transactionId);//苹果的交易订单号
                                                resParam.setFee(rmb);//保存为分

                                                boolean result = PayUtils.checkOrderFromMainServer(finalServerModel.getMainServerRequestUrl(), resParam);
                                                if(result)
                                                {
                                                    orderRecordModel.paySuccess(reqDto.getGameVersion(), diamond, reqDto.getPlayerLv(), payType, payType, reqDto.getServerRuleId(), transactionId);
                                                    orderRecordService.updateOrder(orderRecordModel, false);
                                                    LogUtils.warn("APPSTORE冲值成功 -> " + orderRecordModel.getOutTradeNo());
                                                }
                                                else
                                                {
                                                    LogUtils.debug("主服务器冲值回调返回错误!");
                                                    //主服未通知成功,在玩家下一次登录时来认证服获取一下未通知成功的订单
                                                    orderRecordModel.setStatus(E_RechargeStatus.VERIFY.getCode());
                                                    orderRecordModel.setTcd(transactionId);
                                                    orderRecordModel.setSsid(transactionId);
                                                    orderRecordModel.setChannel(payType);
                                                    orderRecordModel.setPaymentType(payType);
                                                    orderRecordService.updateOrder(orderRecordModel, false);
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    LogUtils.error("验证苹果冲值订单号错误 -> 苹果返回订单号:" + transactionId + "  验证订单的号:" + reqDto.getTransactionId());
                                }
                            } else {
                                LogUtils.error("苹果冲值验证失败 -> " + states);
                            }
                        }
                    }
                    else
                    {
                        LogUtils.error("不能开始验证");
                    }
                }
            }catch (Exception e){
                LogUtils.errorException(e);
                resParam.setErrorMsg(ReturnMessage.PARAM_ERROR.getMsg());
                HttpJsonUtils.httpPost(errorNotifyUrl, resParam.toJSONObject());
            }
        });

        return new BaseResponseDto(ReturnMessage.SUCCESS);
    }

    @ResponseBody
    @RequestMapping(value = HttpFactory.PAY_NOTIFY_PINGPING, method = RequestMethod.POST)
    public String PPCheckOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {

        PPCheckOrderReqParam orderReqDto = new PPCheckOrderReqParam();
        orderReqDto.init(request);
        LogUtils.info("回调参数：" + orderReqDto.toString());
        String sandBoxState = request.getParameter("X-Order-Sandbox");//沙盒状态
        sandBoxState = sandBoxState == null ? "" : sandBoxState;
        if (sandBoxState.equals("1")) {
            //TODO 沙盒状态- -
        }
        if (orderReqDto.isResultOk()) {
            if (orderReqDto.isSuccess()) {
                RechargeParam rechargeParam = new RechargeParam(orderReqDto.getExtraInfo());
                //查询订单
                LogUtils.info("平平回调订单号 -> " + rechargeParam.getOutTradeNo());
                OrderRecordModel orderRecordModel = orderRecordService.findByOutTradeNo(rechargeParam.getOutTradeNo());
                if (orderRecordModel == null) {
                    LogUtils.error("订单不存在:" + rechargeParam.getOutTradeNo());
                    return FAIL_LOWER;
                } else {
                    if(orderRecordModel.getStatus() == E_RechargeStatus.PAY_SUCCESS.getCode())
                    {
                        LogUtils.warn("该订单重复验证 -> outTradeNo:" + orderRecordModel.getOutTradeNo());
                        return SUCCESS_LOWER;
                    }
                    else
                    {
                        ServerModel serverModel = serverMapper.selectByPrimaryKey(Integer.valueOf(rechargeParam.getServerId()));
                        if(serverModel == null)
                        {
                            LogUtils.error("服务器找不到 -> " + rechargeParam.getServerId());
                            return FAIL_LOWER;
                        }
                        else
                        {
                            String payType = PayUtils.getEnumType(SGCommonProto.E_RECHARGE_TYPE.RECHARGE_TYPE_APPSTORE.name());
                            String channel = PayUtils.getEnumType(SGCommonProto.E_PLATFORM_TYPE.PLATFORM_TYPE_APPLE_PINGPING.name());
                            int totalFee = Integer.parseInt(orderReqDto.getAmount().replace(".00", "")) * 100;//转为分
                            boolean result = PayUtils.checkOrderFromMainServer(serverModel.getMainServerRequestUrl(), rechargeParam.getServerId(), rechargeParam.getObjectIndex(), orderReqDto.getExtraInfo(),
                                    rechargeParam.getOutTradeNo(), orderReqDto.getOrderId(), totalFee, payType, channel, false);
                            if(result)
                            {
                                orderRecordModel.paySuccess(rechargeParam.getClientParam(), rechargeParam.getDiamonds(), rechargeParam.getLv(), channel, payType, rechargeParam.getRuleId(), orderReqDto.getOrderId());
                                orderRecordService.updateOrder(orderRecordModel, false);
                                LogUtils.info("平平充值成功 -> " + orderRecordModel.getOutTradeNo());
                                return SUCCESS_LOWER;
                            }
                            else
                            {
                                LogUtils.debug("主服务器冲值回调返回错误!");
                                return FAIL_LOWER;
                            }
                        }
                    }

                }
            } else {
                return FAIL_LOWER;
            }
        } else {
            return FAIL_LOWER;
        }

    }


    /**
     * 抢玩的回调
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = HttpFactory.PAY_NOTIFY_QIANGWAN)
    public String qwNotify(HttpServletRequest request)
    {
        String game_id = request.getParameter("game_id");
        String platformOrderNo = request.getParameter("out_trade_no");
        String price = request.getParameter("price");
        String extend = request.getParameter("extend");
        String sign = request.getParameter("sign");

        if(PayUtils.isNullOrEmpty(game_id, platformOrderNo, price, extend, sign))
        {
            LogUtils.error("QIANG_WAN Notify Error -> game_id:" + game_id + ",platformOrder:" + platformOrderNo + ",price:" + price + ",extend:" + extend + ",sign:" + sign);
            return FAIL_0;
        }

        String str = game_id + platformOrderNo + price + extend + PlatformFactory.QW_CHECK_PAY_KEY;
        LogUtils.info("待加密的串 -> " + str);
        String checkSign = MD5Utils.encode(str);
        if(!sign.equals(checkSign))
        {
            LogUtils.error("QIANG_WAN sign Error -> sign:" + sign + "  checkSign:" + checkSign);
            return FAIL_0;
        }

        try{
            Integer totalFee = Integer.parseInt(price.replace(".00", "")) * 100;//转为分

            RechargeParam rechargeParam = new RechargeParam(extend);

            String outTradeNo = rechargeParam.getOutTradeNo();
            OrderRecordModel orderRecordModel = orderRecordService.findByOutTradeNo(outTradeNo);
            if(orderRecordModel == null)
            {
                LogUtils.error("QIANG_WAN 订单不存在->" + outTradeNo);
                return FAIL_0;
            }

            if(orderRecordModel.getStatus() == E_RechargeStatus.PAY_SUCCESS.getCode())
            {
                LogUtils.warn("该订单重复验证 -> outTradeNo:" + outTradeNo);
                return SUCCESS_1;
            }

            ServerModel serverModel = serverMapper.selectByPrimaryKey(rechargeParam.getServerId());
            if (serverModel == null)
            {
                LogUtils.error("服务器找不到 id为:" + rechargeParam.getServerId());
                return FAIL_0;
            }
            else
            {
                String payType = PayUtils.getEnumType(SGCommonProto.E_RECHARGE_TYPE.RECHARGE_TYPE_APPSTORE.name());
                String channel = PayUtils.getEnumType(SGCommonProto.E_PLATFORM_TYPE.PLATFORM_TYPE_APPLE_QIANGWAN.name());
                boolean result = PayUtils.checkOrderFromMainServer(serverModel.getMainServerRequestUrl(), rechargeParam.getServerId(), rechargeParam.getObjectIndex(), extend, outTradeNo, platformOrderNo, totalFee, payType, channel, false);
                if(result)
                {
                    orderRecordModel.paySuccess(rechargeParam.getClientParam(), rechargeParam.getDiamonds(), rechargeParam.getLv(), channel, payType, rechargeParam.getRuleId(), platformOrderNo);
                    orderRecordService.updateOrder(orderRecordModel, false);
                    LogUtils.debug("充值成功");
                    return SUCCESS_1;
                }
                else
                {
                    LogUtils.error("主服务器返回充值错误");
                    return FAIL_0;
                }
            }
        }catch (Exception e)
        {
            LogUtils.errorException(e);
            return FAIL_0;
        }
    }

    @ResponseBody
    @RequestMapping(value = HttpFactory.PAY_NOTIFY_QUICKSDK)
    public String quicksdkNotify(HttpServletRequest request)
    {
        String nt_data = request.getParameter("nt_data");
        String sign = request.getParameter("sign");
        String md5Sign = request.getParameter("md5Sign");
        if(PayUtils.isNullOrEmpty(nt_data, sign, md5Sign))
        {
            LogUtils.error("QUICKSDK 回调参数错误!");
            return PARAM_ERROR;
        }

        LogUtils.warn("QUICKSDK 回调参数 -> " + nt_data);

        String checkPwd = MD5Utils.encode(nt_data + sign + PlatformFactory.QUICKSDK_MD5_KEY);
        if(!checkPwd.equals(md5Sign))
        {
            LogUtils.error("签名验证不通过 md5Sign:" + md5Sign + ", checkPwd:" + checkPwd);
            return PARAM_ERROR;
        }

        try{
            String decodeData = PayUtils.quicksdkDecode(nt_data, PlatformFactory.QUICKSDK_CALLBACK_KEY);
            LogUtils.warn("QUICKSDK 解密后的数据 -> " + decodeData);
            decodeData = decodeData.replace("<quicksdk_message>", "");
            decodeData = decodeData.replace("</quicksdk_message>", "");
            Map<String, String> map = XMLUtil.doXMLParse(decodeData);
            String isTest = map.get("is_test");
//            String outTradeNo = map.get("game_order");
            String platformOrderNo = map.get("order_no");
            String channel = map.get("channel");
            String channel_uid = map.get("channel_uid");
            String pay_time = map.get("pay_time");
            String amount = map.get("amount").replace(".00", "");
            Integer totalFee = Integer.parseInt(amount) * 100;//要存为分
            String status = map.get("status");
            String extras_params = map.get("extras_params");
            RechargeParam rechargeParam = new RechargeParam(extras_params);
            String outTradeNo = rechargeParam.getOutTradeNo();
//            if(!SpringContext.isDev())
//            {
            boolean test = "1".equals(isTest);
            if(test)
            {
                //测试订单
                LogUtils.info("此订单为测试订单 -> outTradeNo:" + outTradeNo);
//                return SUCCESS_UPPER;
            }
//            }

            OrderRecordModel orderRecordModel = orderRecordService.findByOutTradeNo(outTradeNo);
            if(orderRecordModel == null)
            {
                LogUtils.error("订单不存在 -> " + outTradeNo);
                return "ORDER_NOT_EXIST";
            }
            if(orderRecordModel.getStatus() == E_RechargeStatus.PAY_SUCCESS.getCode())
            {
                LogUtils.error("此订单重复验证 -> outTradeNo:" + outTradeNo);
                return SUCCESS_UPPER;
            }

//            RechargeParam rechargeParam = new RechargeParam(extras_params);

            ServerModel serverModel = serverMapper.selectByPrimaryKey(rechargeParam.getServerId());
            if (serverModel == null)
            {
                LogUtils.error("服务器找不到 id为:" + rechargeParam.getServerId());
                return PARAM_ERROR;
            }
            else
            {
                if("0".equals(status))
                {
                    //支付成功
                    String payType = PayUtils.getEnumType(SGCommonProto.E_RECHARGE_TYPE.RECHARGE_TYPE_QUICKSDK.name());
                    boolean result = PayUtils.checkOrderFromMainServer(serverModel.getMainServerRequestUrl(), rechargeParam.getServerId(), rechargeParam.getObjectIndex(), extras_params, outTradeNo, platformOrderNo, totalFee, payType, channel, test);
                    if(result)
                    {
                        orderRecordModel.paySuccess(rechargeParam.getClientParam(), rechargeParam.getDiamonds(), rechargeParam.getLv(), channel, payType, rechargeParam.getRuleId(), platformOrderNo);
                        orderRecordService.updateOrder(orderRecordModel, false);
                        LogUtils.debug("充值成功");
                        return SUCCESS_UPPER;
                    }
                    else
                    {
                        LogUtils.error("主服务器返回充值错误");
                        return "REWARD_ERROR";
                    }
                }
                else
                {
                    orderRecordModel.setStatus(E_RechargeStatus.PAY_FAILED.getCode());
                    orderRecordModel.setTcd(platformOrderNo);
                    orderRecordModel.setUid(channel_uid);
                    orderRecordService.updateOrder(orderRecordModel, false);
                    return "FAILED";
                }
            }

        }catch (Exception e){
            LogUtils.errorException(e);
            return PARAM_ERROR;
        }
    }


    public static void main(String[] args) {
        String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<quicksdk_message>\n" +
                "<message>\n" +
                "<is_test>3</is_test>\n" +
                "<channel>2</channel>\n" +
                "<channel_uid>5</channel_uid>\n" +
                "<game_order>3</game_order>\n" +
                "<order_no>4</order_no>\n" +
                "<pay_time>d</pay_time>\n" +
                "<amount>r</amount>\n" +
                "<status>e</status>\n" +
                "<extras_params>w</extras_params>\n" +
                "</message>\n" +
                "</quicksdk_message>";
        try {
            str = str.replace("<quicksdk_message>", "");
            str = str.replace("</quicksdk_message>", "");
            Map map = XMLUtil.doXMLParse(str);

            LogUtils.info(map);
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
